﻿Imports System.Data
Imports System.Data.OleDb

Partial Class RecipieDetails
    Inherits System.Web.UI.Page

    Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
        Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("myFirstDatabase").ConnectionString)
        Dim SqlString As String = "Insert into tblcomments(Title,Author,Comments,Article_fkid,SubmittedDate) Values (@f1,@f2,@f3,@f4,@f5)"
        Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
        Dim SubmittedDate As DateTime = Now()
        Dim format As String = "ddd MMM yyyy"
        cmd.CommandType = CommandType.Text
        cmd.Parameters.AddWithValue("@f1", txtTitle.Text)
        cmd.Parameters.AddWithValue("@f2", txtAuthor.Text)
        cmd.Parameters.AddWithValue("@f3", txtcomments.Text)
        cmd.Parameters.AddWithValue("@f4", Request.Params("ID"))
        cmd.Parameters.AddWithValue("@f5", SubmittedDate.ToString(format))
        oleDbConn.Open()
        cmd.ExecuteNonQuery()
        Response.Redirect("RCommentConfirmation.aspx")
    End Sub

    Protected Sub btnTag_Click(sender As Object, e As System.EventArgs) Handles btnTag.Click
        Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("myFirstDatabase").ConnectionString)
        Dim SqlString As String = "INSERT INTO RecipieTagJunction(RecipieID, TagID) Values (@f1,@f2)"
        oleDbConn.Open()

        For Each cb As ListItem In CBLTags.Items
            If cb.Selected Then
                Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
                cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("@f1", Request.Params("ID"))
                cmd.Parameters.AddWithValue("@f2", cb.Value)
                cmd.ExecuteNonQuery()
                Response.Redirect("RCommentConfirmation.aspx")
            End If
        Next

        Dim newTags = tbNewTag.Text.Split(",")
        For Each newTag In newTags
            Dim newTagSql As String = "Insert into tblTags(Tag) values (@f1)"
            Dim cmd As OleDbCommand = New OleDbCommand(newTagSql, oleDbConn)
            cmd.CommandType = CommandType.Text
            cmd.Parameters.AddWithValue("@f1", newTag)
            cmd.ExecuteNonQuery()

            Dim getlastIdCmd As OleDbCommand = New OleDbCommand("SELECT TOP 1 ID from TBLTags ORDER BY ID DESC", oleDbConn)
            Dim dr = getlastIdCmd.ExecuteReader()
            dr.Read()
            Dim lastID = dr.GetValue(0)

            Dim newcmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
            newcmd.CommandType = CommandType.Text
            newcmd.Parameters.AddWithValue("@f1", Request.Params("ID"))
            newcmd.Parameters.AddWithValue("@f2", lastID)
            newcmd.ExecuteNonQuery()
        Next
    End Sub
End Class
